package com.haier.npt.security.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.haier.npt.exception.BizBaseException;
import com.haier.npt.security.dao.SysPermissionDao;
import com.haier.npt.security.domain.SysPermission;
import com.haier.npt.security.i18n.SecurityExceptionCode;
import com.haier.npt.security.i18n.SecurityMessageCode;
import com.haier.npt.security.service.SysPermissionService;
import com.haier.npt.utils.MessageHelper;


/**
 * @Description:权限项服务实现类
 * @author: lixu
 * @date:   2018年7月13日 下午2:27:54   
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionDao, SysPermission> implements SysPermissionService {

    @Autowired
    private SysPermissionDao sysPermissionDao;

    @Autowired
    private MessageHelper messageHelper;
    /**
     * 根据权限项编号查询权限
     */
    @Override
    public List<SysPermission> listPermission(List<Long> permissionIdList) {


        List<SysPermission> sysPermissions = new ArrayList<SysPermission>();
        if (permissionIdList==null || permissionIdList.size() == 0) {
            return sysPermissions;
        }



        EntityWrapper<SysPermission> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("available", 1).and().in("id", permissionIdList).orderBy("sort", true);

        sysPermissions = this.sysPermissionDao.selectList(entityWrapper);

        return sysPermissions;
    }



    /**
     * 添加一个权限项
     *
     * @param sysPermission
     * @return
     */
    public boolean addPermission(SysPermission sysPermission) {
        sysPermission.setAvailable(true);
        sysPermission.setCreatedate(new Date());

        // 验证是否存在   
        EntityWrapper<SysPermission> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("permission_code", sysPermission.getPermissionCode());

        int count = this.sysPermissionDao.selectCount(entityWrapper);
        if (count > 0) {
            throw new BizBaseException(SecurityExceptionCode.PERMISSION_EXISTS);
        }

        sysPermission.setId(IdWorker.getId());

        // 得到pid

        Long pid = sysPermission.getPid();
        if (pid != null) {
            SysPermission parentPermisson = this.sysPermissionDao.selectById(pid);
            // 有父级，查询父级权限， 得到id_path
            if (parentPermisson != null) {
                String idpath = parentPermisson.getIdPath()
                        + sysPermission.getId() + "/";
                sysPermission.setIdPath(idpath);
            } else {
                throw new BizBaseException(SecurityExceptionCode.PERMISSION_NOT_EXISTS);
            }
        } else {
            sysPermission.setIdPath("/" + sysPermission.getId() + "/");
        }
        return this.sysPermissionDao.insert(sysPermission) > 0 ? true : false;
    }

    /**
     * 根据权限项编号删除权限项
     *
     * @param id
     * @return
     */
    public boolean deletePermissionById(Long id) {
        Assert.notNull(id, messageHelper.getMessage(SecurityMessageCode.PERMISSIONID_NOT_NULL));//"permissionId  is not be null"

        // 级联删除下级的权限
        EntityWrapper<SysPermission> entityWrapper = new EntityWrapper<>();
        entityWrapper.like("id_path", "/" + id + "/").or().eq("id", id);

        this.sysPermissionDao.delete(entityWrapper);
        return true;
    }

    /**
     * 获取父权限项Code下面全部的子权限项，包括父本身
     */
    @Override
    public List<SysPermission> listPermissionByParentCode(String parentCode) {
        List<SysPermission> childPermissions = this.sysPermissionDao.listPermissionByParentCode(parentCode);
        return childPermissions;
    }


    @Override
    public List<SysPermission> listPermissionByCodes(List<String> permissionCodes) {
        if (permissionCodes == null || permissionCodes.size() == 0) {
            return new ArrayList<>();
        }
        return sysPermissionDao.listPermissionByCodes(permissionCodes);
    }

    @Override
    public List<SysPermission> listPermissionByPId(Long pId) {
        return sysPermissionDao.listPermissionByPId(pId);
    }
    
    /**
     * 加载所有的权限项目
     */
    public List<SysPermission> listAllPermission() {
        /**
         * 只加载url不为空的权限
         */
        EntityWrapper<SysPermission> entityWrapper = new EntityWrapper<>();
        entityWrapper.isNotNull("url")
            .and().eq("available", true);
        List<SysPermission> allPermissions = this.sysPermissionDao.selectList(entityWrapper);
        return allPermissions;
    }
}
